<?php
/**
 * Created by PhpStorm.
 * User: wxp
 * 日期: 2019/1/23
 * 时间: 12:30
 */

namespace app\modules\admin\controllers;

use Yii;
use app\modules\admin\models\AdminLoginForm;

class AuthController extends Controller
{
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['access']['only'] = ['logout'];
        $behaviors['access']['rules'] = [
            [
                'actions' => ['logout'],
                'allow' => true,
                'roles' => ['@'],
            ]
        ];
        $behaviors['verbs']['actions'] = ['logout' => ['post']];
        return $behaviors;
    }

    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => substr(rand(1000,9999), 0),
                'height' => 50,
                'width' => 100,
                'maxLength' => 4,
                'minLength' => 4,
            ],
        ];
    }

    public function actionLogin()
    {
        $this->layout = false;

        if (!Yii::$app->admin->isGuest) {
            return $this->redirect(['/admin']);
        }

        $model = new AdminLoginForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($model->login()) {
                Yii::$app->session->setFlash('success', '登录成功');
                return $this->redirect(['/admin/default/index']);
            }
        }
        return $this->render('login', [
           'model' => $model,
        ]);
    }

    public function actionLogout()
    {
        Yii::$app->admin->logout();
        return $this->redirect(['/admin/auth/login']);
    }
}